package cs2340.spring13.team3.wheresmystuff.views;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import cs2340.spring13.team3.wheresmystuff.R;
import cs2340.spring13.team3.wheresmystuff.presenters.LoginManager;

/**
 * This class serves as the view for user login and registration, and is the
 * first view the user is presented with upon opening the application.
 */

public class LoginActivity extends Activity implements ILoginView {
	
	private static final int CREATE_ACCOUNT_CALL=100;
	

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;
	boolean registered;
    
    // Values for email and password at the time of the login attempt.
    private String mEmail;
    private String mPassword;

    // The class that manages our login information
    private LoginManager loginManager;
    
	private int count; //the number of log-in attempts so far

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		loginManager = LoginManager.getInstance();
		count=0;
		registered = false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * notifies the screen when a sub-activity completes, and performs the
	 * appropriate actions
	 * 
	 * @param source
	 *            The button from which the click originates
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == CREATE_ACCOUNT_CALL) {
			((EditText) findViewById(R.id.emailField)).setText((String) data
					.getExtras().get("email"));
			((EditText) findViewById(R.id.passwordField)).setText((String) data
					.getExtras().get("password"));
			try {
				loginManager.attemptLogin(getEmailField().getText().toString(),
						getPasswordField().getText().toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * Uses a simple AlertDialog to display a message to the end user regarding
	 * the login process
	 * 
	 * @param message
	 *            The message to display
	 */

	@Override
	public void displayLoginMessage(String title, String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		if (title != null && !TextUtils.isEmpty(title))
			alertDialog.setTitle(title);
		alertDialog.setMessage(message);
		alertDialog.show();
	}

	/**
	 * Returns the text field used to input an email address
	 * 
	 * @return The email text field
	 */

	private EditText getEmailField() {
		return (EditText) findViewById(R.id.emailField);
	}

	/**
	 * Returns the text field used to input a password
	 * 
	 * @return The password text field
	 */

	private EditText getPasswordField() {
		return (EditText) findViewById(R.id.passwordField);
	}
	
	//****************
	
	
	
	
	public static boolean checkInvalidEmail(String email, EditText emailField)
	{
        if (TextUtils.isEmpty(email)) {
    		emailField.setError("Field is required");
            return true;
	    } else if (!email.matches("[a-zA-Z_0-9.]+@[a-zA-Z_0-9.]+.[a-zA-Z]{3}") ) {
	    	emailField.setError("Invalid email");
	        return true;
	    }
        return false;
	}
	
	public static boolean checkInvalidPassword(String password, EditText passwordField)
	{
        if (TextUtils.isEmpty(password)) {
    		passwordField.setError("Field is required");
            return true;
	    } else if (password.length() < 4) {
	            //mPasswordView.setError(getString(R.string.error_invalid_password));
	    		passwordField.setError("Password too short");
	            return true;
	    }
        return false;
	}
	
	//**************
	
	private boolean checkInvalidEmailPassword()
	{
		return checkInvalidEmail(mEmail, getEmailField() ) || checkInvalidPassword(mPassword, getPasswordField() );
	}
	
	/**
	 * Uses the LoginManager (presenter) to attempt a login with the credentials in the text fields when the
	 * corresponding button is clicked
	 *
	 * @param source The button from which the click originates
	 */
	
	public void onLoginClick(View source)
	{
		//myLoginManager.attemptLogin(getEmailField().getText().toString(), getPasswordField().getText().toString());
		if (mAuthTask != null) {
            return;
		}
		
		 // Reset errors.
        getEmailField().setError(null);
        getPasswordField().setError(null);
		
        // Store values at the time of the register attempt.
		mEmail = getEmailField().getText().toString();
		mPassword = getPasswordField().getText().toString();
		
		boolean cancel = checkInvalidEmailPassword();
        
        if (!cancel && count<3){
            //mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            mAuthTask = new UserLoginTask(this, mEmail, mPassword);
            mAuthTask.execute((Void) null);
            count++;
        }
        else if(count>=3) {
        	
        }
        
	}
	
	/**
	 * Uses the LoginManager (presenter) to attempt to register a new user with the credentials
	 * in the text fields when the corresponding button is clicked
	 *
	 * @param source The button from which the click originates
	 */
	
	public void onRegisterClick(View source)
	{
		if (mAuthTask != null || registered == true) {
            return;
		}
		// Reset errors.
        getEmailField().setError(null);
        getPasswordField().setError(null);
		
        //start new Activity
		Intent i = new Intent(LoginActivity.this, CreateAccountActivity.class);
		startActivityForResult(i, CREATE_ACCOUNT_CALL);
		
	}
	
	
    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
            private Activity activity;
            private String email, password;
            
            public UserLoginTask(Activity applicationActivity, String email, String pass) {
                    this.activity = applicationActivity;
                    this.email = email;
                    this.password = pass;
            }
            
            @Override
            protected Boolean doInBackground(Void... params) {
                    try {
                            return loginManager.attemptLogin(this.email, this.password);
                    } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return false;
                    }
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                    mAuthTask = null;
                    if (success) {
                    	displayLoginMessage("Login Successful", "Current user: " + loginManager.getUser().getEmail());
                    	
                    } else {
                    	displayLoginMessage("Login Failed", "Please try again.");
                    }
            }

            @Override
            protected void onCancelled() {
                    mAuthTask = null;
            }
    }
	

}
